#include "hnsd_usart.h"

// U1_TX: PA9
// U1_RX: PA10
void usart_init(void)
{
	//1. GPIO口的配置
	RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA,ENABLE);	
	GPIO_InitTypeDef p;
	p.GPIO_Mode = GPIO_Mode_AF;
	p.GPIO_Pin = GPIO_Pin_9 | GPIO_Pin_10;
	p.GPIO_PuPd = GPIO_PuPd_NOPULL;
	p.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_Init(GPIOA,  &p);
		
	GPIO_PinAFConfig(GPIOA, GPIO_PinSource9, GPIO_AF_USART1);
	GPIO_PinAFConfig(GPIOA, GPIO_PinSource10, GPIO_AF_USART1);

	//2.usart配置
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE);
	
	USART_InitTypeDef u;
	u.USART_BaudRate = 115200;	
	u.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
	u.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
	u.USART_Parity = USART_Parity_No;
	u.USART_StopBits = USART_StopBits_1;
	u.USART_WordLength = USART_WordLength_8b;

	USART_Init(USART1, &u);	
	
	
	/* 3.配置串口中断（如果要中断） */
		
	//USART_ITConfig(USART1,USART_IT_TC,ENABLE);
	USART_ITConfig(USART1,USART_IT_RXNE,ENABLE);	//接收寄存器非空时，触发中断
	
	/* 4.配置NVIC（如果配置了中断） */
	//NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);	
	//NVIC_InitTypeDef n;
	//n.NVIC_IRQChannel						=	USART1_IRQn;
	//n.NVIC_IRQChannelPreemptionPriority	=	2;
	//n.NVIC_IRQChannelSubPriority			=	2;
	//n.NVIC_IRQChannelCmd					=	ENABLE;
	//NVIC_Init(&n);
	
	//5.使能串口
		
	USART_Cmd(USART1, ENABLE);	
	
}

void Usart_SendByte( USART_TypeDef * USARTx, uint8_t ch)
{
	/* 发送一个字节数据到USART */
	USART_SendData(USARTx,ch&0xff);		
	/* 发送数据完毕 */
	while (USART_GetFlagStatus(USARTx, USART_FLAG_TC) == RESET);	
}
uint8_t Usart_ReceiveByte( USART_TypeDef * USARTx)
{
	
	/* 等待接收数据寄存器非空 */
	while(USART_GetFlagStatus(USARTx, USART_FLAG_RXNE) == RESET);
	/* 接收一个字节数据 */
	return USART_ReceiveData(USARTx)&0xff;
}


int fputc(int c, FILE *stream)
{
	USART1->SR;	
	USART_SendData(USART1, c & 0xff);
	while( USART_GetFlagStatus(USART1, USART_FLAG_TC) == RESET){};	
  return(c);
}



